<template>

	<div id="bodyContainer" style="height:100%;">
		<div id="topNav">
			<el-row>
				<el-col :span="10">
					<div style="padding-top:2px;padding-left:10px;">
						<img src="../assets/images/logo1.png" style="width:100px" />
					</div>
					<div style="font-size:20px;padding-left:10px;font-weight: bold">智慧校园综合管理平台<span v-if="sysVersion != ''" style="font-size: 13px">&nbsp;V{{sysVersion}}</span></div>
				</el-col>
				<el-col :span="14" style="text-align: right">
					<el-popover ref="messagePopver" placement="bottom" trigger="hover">
						<el-table border :data="messageDatas" style="width: 100%">
							<el-table-column :show-overflow-tooltip="true" align="center">
								<template slot-scope="scope">
									<el-tag v-if="scope.row.isreaded" type="success">已读</el-tag>
									<el-tag v-else type="danger">未读</el-tag>
								</template>
							</el-table-column>
							<el-table-column :show-overflow-tooltip="true" align="center" label="类型">
								<template slot-scope="scope">
									<span v-if="scope.row.type == 'bookinfo'">通知</span>
									<span v-if="scope.row.type == 'fatal'">故障</span>
									<span v-if="scope.row.type == 'Error'">异常</span>
								</template>
							</el-table-column>
							<el-table-column :show-overflow-tooltip="true" align="center" label="标题">
								<template slot-scope="scope">
									<span style="cursor: pointer" title="点击查看详情" @click="getMessageDetail(scope.row)">{{scope.row.title}}</span>
								</template>
							</el-table-column>
						</el-table>
						<div style="width: 100%;text-align: center;padding-top: 8px">
							<a style="text-decoration: none;cursor: pointer;font-size:13px;color :#20A0FF;" @click="getHistoryMessage">查看更多</a>
						</div>
					</el-popover>
					<el-badge :value="unReadCount" :max="100" class="item" style="top: 25px;right: 32px">
						<i class="fa fa-bell" style="font-size: 20px;color: #CC9966; cursor: pointer" v-popover:messagePopver></i>
					</el-badge>
					<el-button type="primary" v-if="!hasLogin" @click="Login" class="vertail-middle" style="right:10px"> <i class="el-icon-eleg-icon_profile el-icon--left"></i>{{$t('message.login')}}
					</el-button>
					<el-dropdown v-if="hasLogin" @command="handleCommand" style="top: 25px;right: 5px;">
						<span class="el-dropdown-link" style="cursor: pointer;">
							<i class="fa fa-user-circle-o" style="font-size:20px"></i>
							<span style="font-size: 16px">{{nickName}}</span>
							<i class="el-icon-caret-bottom"></i>
						</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item style="font-size: 13px" command="a"><i class="el-icon-eleg-icon_lock el-icon--left"></i>{{$t('message.resetPassword')}}</el-dropdown-item>
							<el-dropdown-item style="font-size: 13px" command="b"><i class="el-icon-star-on el-icon--left"></i>{{$t('message.resetNickName')}}</el-dropdown-item>
							<el-dropdown-item divided style="font-size: 13px" command="c"><i class="fa fa-power-off" style="padding-right: 9px"></i>{{$t('message.logout')}}</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</el-col>
			</el-row>
		</div>
		<components :is="currentView" v-on:changeView="changeView"></components>
		<!-- 修改密码 -->
		<el-dialog title="修改密码" v-model="changePasswordDialog" :show-close="false" :class="[dialog-tiny-width]">
			<el-form id="form" ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item :label="$t('message.oldPassword')" prop="OldPassword">
					<el-input v-model="form.OldPassword" type="password" required name="OldPassword" id="OldPassword"></el-input>
				</el-form-item>
				<el-form-item :label="$t('message.newPassword')" prop="NewPassword">
					<el-input v-model="form.NewPassword" type="password" required name="NewPassword" id="NewPassword"></el-input>
				</el-form-item>
				<el-form-item :label="$t('message.confirmPassword')" prop="CheckPwd">
					<el-input v-model="form.CheckPwd" type="password" required name="CheckPwd" id="CheckPwd"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="changePasswordDialog = false">取 消</el-button>
				<el-button type="danger" @click="resetForm">清 空</el-button>
				<el-button type="primary" @click="confirmChangePassword('form')">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 修改昵称 -->
		<el-dialog title="修改昵称" v-model="changeNameDialog" :show-close="false" :class="[dialog-tiny-width]">
			<el-form id="nickNameForm" ref="nickNameForm" :model="nickNameForm" :rules="nickNameRules" label-width="100px">
				<el-form-item label="昵称" prop="nickname">
					<el-input v-model="nickNameForm.nickname" type="text" required></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="changeNameDialog = false">取 消</el-button>
				<el-button type="danger" @click="resetNameForm">清 空</el-button>
				<el-button type="primary" @click="confirmChangeName('nickNameForm')">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 更多通知消息 -->
		<el-dialog title="消息通知历史列表" v-model="messageHistoryDialog" :class="[dialog-small-width]">
			<el-table border :data="messageHistoryDatas" style="width: 100%">
				<el-table-column :show-overflow-tooltip="true" align="center">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.isreaded" type="success">已读</el-tag>
						<el-tag v-else type="danger">未读</el-tag>
					</template>
				</el-table-column>
				<el-table-column :show-overflow-tooltip="true" align="center" label="类型">
					<template slot-scope="scope">
						<span v-if="scope.row.type == 'bookinfo'">通知</span>
						<span v-if="scope.row.type == 'fatal'">故障</span>
						<span v-if="scope.row.type == 'Error'">异常</span>
					</template>
				</el-table-column>
				<el-table-column :show-overflow-tooltip="true" align="center" label="标题">
					<template slot-scope="scope">
						<span style="cursor: pointer" title="点击查看详情" @click="getMessageDetail(scope.row)">{{scope.row.title}}</span>
					</template>
				</el-table-column>
				<el-table-column :show-overflow-tooltip="true" align="center" property="time" label="时间">
				</el-table-column>
			</el-table>
			<div class="block" style="text-align:right;float: right;">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes,prev, pager, next, jumper" :total="totalSize">
				</el-pagination>
			</div>
		</el-dialog>
		<!-- 消息详情 -->
		<el-dialog title="消息通知详情" v-model="messageDetailDialog" :class="[dialog-small-width]" @close="closeMessageDetail">
			<el-form :model="messageDetailForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="类型:">
					<span v-if="messageDetailForm.type == 'bookinfo'">通知</span>
					<span v-if="messageDetailForm.type == 'fatal'">故障</span>
					<span v-if="messageDetailForm.type == 'Error'">异常</span>
				</el-form-item>
				<el-form-item label="时间:">
					<span>{{messageDetailForm.time}}</span>
				</el-form-item>
				<el-form-item label="标题:">
					<span>{{messageDetailForm.title}}</span>
				</el-form-item>
				<el-form-item label="描述:">
					<span>{{messageDetailForm.msg}}</span>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>
<script>
	import Vue from 'vue'
	import locale from 'element-ui/lib/locale'
	import cnlang from 'element-ui/lib/locale/lang/zh-CN'
	import enlang from 'element-ui/lib/locale/lang/en'
	import $ from 'jquery'
	import { HttpServer, GloabFun, Animation } from '../assets/js/common.js'

	const JSEncrypt = require("jsencrypt"); // 引入模块
	const encrypt = new JSEncrypt.JSEncrypt(); // 实例化加密对象
	// 主页面
	const Home = resolve => require(['./Home/Index1.vue'], resolve) //上方导航栏

	export default {
		components: {
			Home
		},
		data() {
			//新密码验证
			var create_checkPassword = (rule, value, callback) => {
				if(this.form.NewPassword === '') {
					callback(new Error('密码不能为空'));
				} else if(!((/^[0-9a-zA-Z_]{6,20}$/).test(this.form.NewPassword))) {
					callback(new Error('密码必须为6-20位数字、字母或下划线'));
				} else {
					callback();
				}
			}
			//再次输入密码验证
			var create_checkPass = (rule, value, callback) => {
				if(this.form.CheckPwd === '') {
					callback(new Error('请再次输入密码'));
				} else if(this.form.CheckPwd !== this.form.NewPassword) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			return {
				sysVersion: '',
				publicKey: '',
				form: {
					OldPassword: "",
					NewPassword: "",
					CheckPwd: ""
				},
				rules: {
					OldPassword: [{
						required: true,
						trigger: 'blur',
						message: this.$t('message.oldPasswordRule')
					}],
					NewPassword: [{
						required: true,
						validator: create_checkPassword,
						trigger: 'blur'
					}],
					CheckPwd: [{
						required: true,
						validator: create_checkPass,
						trigger: 'blur'
					}]
				},
				currentView: 'Home',
				hasLogin: true,
				isHome: true,
				changePasswordDialog: false,
				changeNameDialog: false,
				nickName: GloabFun.getNickName(),
				nickNameForm: {
					nickname: GloabFun.getNickName()
				},
				nickNameRules: {
					nickname: [{
						required: true,
						trigger: 'blur',
						message: '昵称不能为空'
					}],
				},
				messageDatas: [],
				unReadCount: 0,
				currentPage: 1,
				pageSize: 10,
				totalSize: 0,
				messageHistoryDatas: [],
				messageHistoryDialog: false,
				messageDetailDialog: false,
				messageDetailForm: {}
			}
		},
		methods: {
			handleCommand(command) {
				if(command === "a") {
					this.changePassword();
				} else if(command === "b") {
					this.changeNickName();
				} else {
					this.cancelLogin();
				}
			},
			Login() {
				clearInterval(window.deviceIntervalid);
				clearInterval(window.deviceDetailIntervalid);
				this.$router.push({
					path: '/Login'
				});
			},
			//退出登录
			cancelLogin() {
				// GloabFun.clearRecordPreview.call(this);
				HttpServer.httpPost.call(this, '/Api/User/Logout', {}, function(response) {}, function(response) {
					// console.log('退出登录response',response);
					if(response.data.code === 0) {
						this.$notify({
							title: '成功',
							message: this.$t('message.logoutSuccess'),
							type: 'success',
							duration: 2500
						});
						this.$router.push({
							path: '/Login'
						});
						GloabFun.clearLoginInfo();
					} else {
						this.$router.push({
							path: '/Login'
						});
						GloabFun.clearLoginInfo();
					}
				});
			},
			changeView(view) {
				Animation.animation($("#bodyContainer"), function() {
					this.currentView = view;
				}.bind(this));
			},
			//修改昵称弹窗
			changeNickName() {
				this.changeNameDialog = true;
			},
			resetNameForm() {
				this.nickNameForm = {
					nickname: ''
				}
			},
			confirmChangeName(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						var param = {
							keyid: parseInt(GloabFun.getKeyId()),
							nickname: this.nickNameForm.nickname
						}
						HttpServer.httpPost.call(this, '/Api/User/Change/info', param, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.$notify({
									title: '成功',
									message: '修改成功,请重新登录',
									type: 'success',
									duration: 2500
								});
								clearInterval(window.deviceIntervalid);
								clearInterval(window.deviceDetailIntervalid);
								this.$router.push({
									path: '/Login'
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					} else {
						return false;
					}
				});
			},
			//公钥格式
			trim(str, is_global) {
				var result;
				result = str.replace(/(^\s+)|(\s+$)/g, "");
				if(is_global.toLowerCase() == "g") {
					result = result.replace(/\s/g, "");
				}
				return result;
			},
			//修改密码弹窗
			changePassword() {
				this.changePasswordDialog = true;
				//获取公钥
				HttpServer.httpGet.call(this, "/Api/User/LoginKey/Js", function(response) {}, function(response) {
					this.publicKey = this.trim(response.data.key, "g")
				});
			},
			resetForm() {
				this.form = {
					OldPassword: "",
					NewPassword: "",
					CheckPwd: ""
				};
			},
			//确认
			confirmChangePassword(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						encrypt.setPublicKey(this.publicKey);
						var param = {
							keyid: parseInt(GloabFun.getKeyId()),
							oldpassword: encrypt.encrypt(this.form.OldPassword),
							newpassword: encrypt.encrypt(this.form.NewPassword),
							m: 1
						}
						HttpServer.httpPost.call(this, '/Api/User/Change/Password', param, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.$notify({
									title: '成功',
									message: '密码修改成功，请重新登录',
									type: 'success',
									duration: 2500
								});
								this.$router.push({
									path: '/Login'
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					} else {
						return false;
					}
				});
			},
			//去掉时间中的T
			formateData(array) {
				for(var i = 0; i < array.length; i++) {
					var index1 = array[i].UpdateDate.indexOf("T");
					array[i].UpdateDate = array[i].UpdateDate.substring(0, index1) + " " + array[i].UpdateDate.substring(index1 + 1, index1 + 9);
				}
			},
			//获取用户的所有消息列表 -- 用于右上角显示的
			getMessageList() {
				HttpServer.httpPost.call(this,'/Api/User/GetMessageList',{UserId: parseInt(GloabFun.getKeyId()),index: 1, pagesize: 10, filter: ''},function(response){}, function(response){
					// console.log('消息列表',response)
					this.messageDatas = response.data.info;
					this.unReadCount = response.data.unreadcount;
				})
			},
			getHistoryMessage(){
				this.getHistoryMessageList();
				this.messageHistoryDialog = true;
			},
			//获取历史消息列表
			getHistoryMessageList() {
				HttpServer.httpPost.call(this,'/Api/User/GetMessageList',{UserId: parseInt(GloabFun.getKeyId()),index: this.currentPage, pagesize: this.pageSize, filter: ''},function(response){}, function(response){
					// console.log('更多消息列表',response)
					if(response.data.code === 0){
						this.messageHistoryDatas = response.data.info;
						this.totalSize = response.data.total;
					}else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				})
			},
			handleCurrentChange(val){
				this.currentPage = val;
				this.getHistoryMessageList();
			},
			handleSizeChange(val){
				this.pageSize = val;
				this.getHistoryMessageList();
			},
			getMessageDetail(row) {
				this.messageDetailDialog = true;
				this.messageDetailForm = row;
			},
			closeMessageDetail() {
				HttpServer.httpPost.call(this,'/Api/User/UpdateMessageStatus',{isreadedmessageids: [this.messageDetailForm.keyid], UserId: parseInt(GloabFun.getKeyId())}, function(response){}, function(response){
					this.getMessageList();
					this.getHistoryMessageList();
				})
			},
		},
		created() {
			if(GloabFun.getToken() == '') {
				this.hasLogin = false;
				this.$router.push({
					path: '/Login'
				});
			} else {
				this.getMessageList();
				//查询系统版本
				HttpServer.httpGet.call(this, '/Api/System/Version', function(response) {}, function(response) {
					// console.log('系统版本',response);
					this.sysVersion = response.data.version;
				});
				this.messageIntervalid = setInterval(() => {
					this.getMessageList();
				}, 30000)
			}
		},
		beforeDestroy() {
			clearInterval(this.messageIntervalid);
		},
	}
</script>
<style scoped>
	@import '../assets/css/font-awesome-4.7.0/css/font-awesome.css';
</style>
<style scoped lang="less">
	@headerH: 50PX;
	#topNav {
		height: @headerH;
		// position: relative;
		// z-index: 2;
		// .el-menu-demo {
		// 	height: @headerH;
		// }
		.right-nav {
			font-size: 15px;
			float: right !important;
			top: 15px;
			right: 10px;
		}
	}
</style>